const {
	Service
} = require('uni-cloud-router')
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate

module.exports = class SearchService extends Service {
	async getCityList() {
		const coll = uniCloud.database().collection("t3ds-region");
		return coll.get()
	}
	
	async getNeareastCity({
		userLocation
	}) {
		try {
			if (userLocation) {
				let res = await db.collection("t3ds-region").where({
					location: dbCmd.geoNear({
						geometry: new db.Geo.Point(userLocation.longitude, userLocation.latitude)
					})
				}).field({
					city: true,
					name: true,
					wxPubConfig: true
				}).limit(1).get()
				if (res.data.length) {
					let data = res.data[0]
					delete data.wxPubConfig.appId
					delete data.wxPubConfig.appSecret
					return data
				}
			} else {
				let res = await db.collection("t3ds-region").field({
					city: true,
					name: true,
					wxPubConfig: true,
          location: true
				}).limit(1).get()
				if (res.data.length) {
					let data = res.data[0]
					delete data.wxPubConfig.appId
					delete data.wxPubConfig.appSecret
					return data
				}
			}
			
		} catch (e) {
			throw e
		}
	}
}
